package com.freestyle.seatabusiness.account.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.freestyle.easyshiro.intercept.method.SessionTokenUtils;
import com.freestyle.easyshiro.intercept.method.SessionTokenUtils;
import com.freestyle.seatabusiness.account.dao.AccountTblMapper;
import com.freestyle.seatabusiness.api.models.AccountTbl;
import com.freestyle.seatabusiness.api.service.AccountServiceQuery;
import com.freestyle.sentinel.SentinelResponseEntity;
import com.freestyle.sentinel.annotation.SentinelResourceGlobalHandle;
import org.apache.dubbo.config.annotation.DubboService;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.cache.annotation.Cacheable;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * Created by rocklee on 2022/3/25 11:51
 */
@DubboService(cluster = "failover") //默认重试2次
public class AccountQueryServiceImp implements AccountServiceQuery {
  @Resource
  private AccountTblMapper accountTblMapper;

  @Override
  @SentinelResource(value ="getAccountList")
  @SentinelResourceGlobalHandle
  @RequiresPermissions(value = {"P1"})
  //sync：设置如果缓存过期是不是只放一个请求去请求数据库，其他请求阻塞，默认是false。
  @Cacheable(value="default",key = "'getAccountList-'+#prefix+'-'+#pageNo+'-'+#pageSize")
  //@Cacheable(value="byteGetAllJobBaseInfo",key="'getAllJobBaseInfo-'+#station+'-'+T(Boolean).toString(#skipInvalidJob)")
  public SentinelResponseEntity<Page<AccountTbl>> getAccountList(String prefix, int pageNo, int pageSize) {
      if (pageNo==8)
        throw new IllegalStateException("test exception");
    SentinelResponseEntity<Page<AccountTbl>> entity=SentinelResponseEntity.fromResult(0,accountTblMapper.selectPage(new Page<>(pageNo, pageSize), Wrappers.lambdaQuery(AccountTbl.class)
            .ge(AccountTbl::getUserId, prefix)));;
    /*try {
      Thread.sleep(1200);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }*/
    return entity;
  }

  @Override
  public SentinelResponseEntity<String> sayHello(String a) {
    return SentinelResponseEntity.fromResult(0,"hello "+a);
  }

  @Override
  @SentinelResource(value ="getAccountList")
  @SentinelResourceGlobalHandle
  @RequiresPermissions(value = {"P1"})
  @Cacheable(value="default",key = "'getToken-'+#t")
  public SentinelResponseEntity<String> getToken(String t)
  {
    System.out.println(Thread.currentThread().getId()+"   "+t);
    return SentinelResponseEntity.fromResult(0, SessionTokenUtils.getToken().toString());
  }

}
